package com.fdzc.controller;

import com.fdzc.model.user;
import com.fdzc.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class userController {
    @Autowired
    private userService userservice;

    /*
     *通过异步方式实现登陆
     */
    @RequestMapping("/login")
    @ResponseBody
    public Map<String,String> loginAjax(user u, HttpSession session){
        Map<String,String> result=new HashMap<String, String>();
        user u1 = userservice.login(u);
        if(u1!=null){
            session.setAttribute("loginUser",u1);
            result.put("code","1");
            result.put("msg","login Success");
        }
        else{
            result.put("code","0");
            result.put("msg","login Fails");
        }
        return result;
    }

    /**
     * 登录成功后跳转
     * @return
     * @throws Exception
     */
    @RequestMapping("/back")
    public ModelAndView toBack() throws Exception {
        ModelAndView mv=new ModelAndView();
        //设置视图
        mv.setViewName("back");
        return mv;
    }

    @RequestMapping("/checkuname")
    @ResponseBody
    public Map<String,String> checkuname(String username){
        Map<String,String> map=new HashMap<>();
        user u = userservice.selectByName(username);
        if(u != null){
            map.put("code","1");
            map.put("msg","User Exist");
        }
        else{
            map.put("code","0");
            map.put("msg","User is Ok");
        }
        return map;
    }

    @RequestMapping("/user")
    public ModelAndView toRegister() throws Exception {
        ModelAndView mv=new ModelAndView();
        //设置视图
        mv.setViewName("user");
        return mv;
    }

    @RequestMapping("/saveUser")
    @ResponseBody
    public Map<String,String> saveUser(user u){
        Map<String,String> result=new HashMap<String, String>();
        userservice.saveUser(u);
        result.put("code","1");
        result.put("msg","save Success");
        return result;
    }
}
